package com.springBoot.springBootSysCore.filter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

/**
 * 输出响应
 * Created by timo on 2017/12/27.
 */
public class CustomHttpServletResponse extends HttpServletResponseWrapper {
    private ServletOutputStream outputStream;

    private PrintWriter writer;

    private CustomServletOutputStream cout;


    /**
     * Constructs a response adaptor wrapping the given response.
     *
     * @throws IllegalArgumentException if the response is null
     */
    public CustomHttpServletResponse(HttpServletResponse response) {
        super(response);
    }


    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        if (writer != null) {
            throw new IllegalStateException("getWriter() has already been called on this response.");
        }
        if (outputStream == null) {
            outputStream = getResponse().getOutputStream();
            cout = new CustomServletOutputStream(outputStream);
        }
        return cout;

    }
    @Override
    public PrintWriter getWriter() throws IOException {
        if (outputStream != null) {
            throw new IllegalStateException("getOutputStream() has already been called on this response.");
        }

        if (writer == null) {
            cout = new CustomServletOutputStream(getResponse().getOutputStream());
            writer = new PrintWriter(new OutputStreamWriter(cout, getResponse().getCharacterEncoding()), true);
        }
        return writer;

    }


    @Override
    public void flushBuffer() throws IOException {
        if (writer != null) {
            writer.flush();
        } else if (outputStream != null) {
            cout.flush();
        }
    }

    public byte[] getCopy() {
        if (cout != null) {
            return cout.getCopy();
        } else {
            return new byte[0];
        }

    }


}
